package misscl.online.slh_gym.controller;

import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import misscl.online.slh_gym.entity.Sms;
import misscl.online.slh_gym.entity.User;
import misscl.online.slh_gym.util.*;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;


/**
 * project name: IntelliJ IDEA
 * Date: 2022/10/26 20:28
 *
 * @PackageName: run.theo.mallauth.controller
 * @ClassName: SmsController
 * @Author: Theo
 * @Version:
 * @Description:
 */
@RestController
@RequestMapping(("/sms"))
public class SmsController {

    private String smsCode;
    @Autowired
    private UserController userController;
    private String phone;
    @PostMapping("/sendCode")
    public AjaxResult sendCode(@RequestBody Sms sms){
        int appid = 1400753948;
        String appkey = "2204cefbe4b9e730911c44e897357b4b";
        int templateId = 1582877; //模板ID
        String smsSign = "灵动平台个人网";

        smsCode = RandCode.getCode();
        phone = sms.getPhone();

//        //验证码写入redis 存储时间60m
//        redisUtil.set(smsCode,phone,60);

        System.out.println(smsCode);

        //13358286070
//        try{
//            String[] params = {
//                    smsCode//验证码
//            }; //短信中的参数
//            SmsSingleSender ssender = new SmsSingleSender(appid,appkey);
//            SmsSingleSenderResult result = ssender.sendWithParam("86",sms.getPhone(),templateId,
//                    params,smsSign,"","");
//            System.out.println(result.errMsg);
//            if ("ok".equalsIgnoreCase(result.errMsg)){
//                return AjaxResult.ok("发送成功");
//            }else{
//                return AjaxResult.error("发送失败");
//            }
//        }catch (HTTPException e){
//            e.printStackTrace();
//        }catch (JSONException e){
//            e.printStackTrace();
//        }catch (IOException e){
//            e.printStackTrace();
//        }
        return AjaxResult.error("发送失败");
    }

    @PostMapping("/login")
    public AjaxResult login(@RequestBody Sms sms, HttpServletRequest request, HttpServletResponse resp){
        System.out.println(smsCode + "--->666666");
        System.out.println(phone + "--->777777");

        if (phone == null || smsCode == null)
            return AjaxResult.error("登录失败，短信或手机号错误！！！");
        if (phone.equals(sms.getPhone()) && smsCode.equals(sms.getCode())){
            //1.判断redis是否有这个token
            String authorization = request.getHeader("authorization");
            //2.判断数据库是否有此用户，没有的话注册，有的话直接登录
            User user = userController.getUserByPhone(phone);
            System.out.println(user +"--->88888");
            if (user != null){
                if (user.getId() != -1){
                    //3.生成token
                    String userId = String.valueOf(user.getId());

                    String token =  JwtUtils.generateToken(userId);

                    System.out.println("token-----"+token);
                    //4.添加响应头
                    resp.setHeader("authentication",token);
    //                        //5.存入redis
    //                        redisUtil.set(token,user);
                    return AjaxResult.ok("登录成功！");
                }else {
                    return AjaxResult.error("调用用户模块失败！");
                }
            }else {
                //注册
                //生成用户唯一ID
                String uuid16 = UuidUtils.getUUID16();
                //随机分配名字
                String name = NameUtil.getName();

                System.out.println("uuid16-----"+uuid16);
                System.out.println("name-----"+name);

                User user1 = new User();
                user1.setPhone(phone);
                user1.setUserName(name);
                user1.setAccount(uuid16);
                user1.setRegTime(new SimpleDateFormat("yyyy-MM-dd hh:ss:mm").format(new Date(System.currentTimeMillis())));
    //                    setUuid();

                User user2 = userController.saveByPhone(user1);
                System.out.println(user2+"9999999");
                if (user2.getId() != -1 && user2.getId() !=0 ){
                    //3.生成token

                    String newUserId = String.valueOf(user2.getId());

                    String token = JwtUtils.generateToken(newUserId);
                    //4.添加响应头
                    resp.setHeader("authentication",token);
                    //5.存入redis

    //                        redisUtil.set(token,user2);
                    return AjaxResult.ok("注册并登录成功！");
                }else{
                    return AjaxResult.error("注册失败！！！");
                }
            }
        }else {
            //登录失败
            return AjaxResult.error("登录失败，短信或手机号错误！！！");
        }
    }

}

